import { createRouter, createWebHashHistory } from 'vue-router'

// 页面组件导入
const HomePage = () => import('@/views/home/HomePage.vue')
const LoginPage = () => import('@/views/user/LoginPage.vue')
const RegisterPage = () => import('@/views/user/RegisterPage.vue')
const ProductDetail = () => import('@/views/product/ProductDetail.vue')
const ProductList = () => import('@/views/product/ProductList.vue')
const BrandProducts = () => import('@/views/product/BrandProducts.vue')
const SearchResults = () => import('@/views/product/SearchResults.vue')
const ShoppingCart = () => import('@/views/cart/ShoppingCart.vue')
const UserCenter = () => import('@/views/user/UserCenter.vue')
const OrderList = () => import('@/views/user/OrderList.vue')
const Favorites = () => import('@/views/user/Favorites.vue')
const SellPage = () => import('@/views/sell/Sell.vue')
const UserManagementComponent = () => import('@/components/user/UserManagementComponent.vue')
const UserDetail = () => import('@/components/user/UserDetail.vue')
const NewsManagementComponent = () => import('@/components/news/NewsManagementComponent.vue')
const ProductManagementComponent = () => import('@/components/product/ProductManagementComponent.vue')
const CategoryProducts = () => import('@/views/product/CategoryProducts.vue')
const AddressManagementComponent = () => import('@/components/address/AddressManagementComponent.vue')
const OrderConfirmation = () => import('@/views/order/OrderConfirmation.vue')
const AlipayPayment = () => import('@/views/order/AlipayPayment.vue')
const TestHighlight = () => import('@/views/product/TestHighlight.vue')
const HighlightTest = () => import('@/views/product/HighlightTest.vue')


// 账户安全组件导入
const AccountSecurityComponent = () => import('@/components/user/AccountSecurityComponent.vue')

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomePage,
    meta: {
      title: '首页 - EasyBuy 电商平台'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginPage,
    meta: {
      title: '用户登录 - EasyBuy',
      requiresGuest: true // 只允许游客访问
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterPage,
    meta: {
      title: '用户注册 - EasyBuy',
      requiresGuest: true
    }
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: ProductDetail,
    meta: {
      title: '商品详情 - EasyBuy'
    }
  },
  {
    path: '/products',
    name: 'ProductList',
    component: ProductList,
    meta: {
      title: '商品列表 - EasyBuy'
    }
  },
  {
    path: '/brand/:id',
    name: 'BrandProducts',
    component: BrandProducts,
    meta: {
      title: '品牌商品 - EasyBuy'
    }
  },
  {
    path: '/search',
    name: 'SearchResults',
    component: SearchResults,
    meta: {
      title: '搜索结果 - EasyBuy'
    }
  },
  {
    path: '/cart',
    name: 'ShoppingCart',
    component: ShoppingCart,
    meta: {
      title: '购物车 - EasyBuy'
    }
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: UserCenter,
    meta: {
      title: '个人中心 - EasyBuy',
      requiresAuth: true // 需要登录
    },
    children: [
      {
        path: '',
        name: 'UserDetail',
        component: UserDetail,
        meta: {
          title: '个人中心 - EasyBuy',
          requiresAuth: true
        }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/user/Profile.vue'),
        meta: {
          title: '用户信息 - EasyBuy',
          requiresAuth: true
        }
      },
      {
        path: 'orders',
        name: 'UserOrders',
        component: OrderList,
        meta: {
          title: '我的订单 - EasyBuy',
          requiresAuth: true
        }
      },
      {
        path: 'favorites',
        name: 'UserFavorites',
        component: Favorites,
        meta: {
          title: '我的收藏 - EasyBuy',
          requiresAuth: true
        }
      },
      {
        path: 'management',
        name: 'UserManagement',
        component: UserManagementComponent,
        meta: {
          title: '用户管理 - EasyBuy',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'news',
        name: 'NewsManagement',
        component: NewsManagementComponent,
        meta: {
          title: '新闻管理 - EasyBuy',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'product',
        name: 'ProductManagement',
        component: ProductManagementComponent,
        meta: {
          title: '商品管理 - EasyBuy',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'security',
        name: 'AccountSecurity',
        component: AccountSecurityComponent,
        meta: {
          title: '账户安全 - EasyBuy',
          requiresAuth: true
        }
      },
      {
        path: 'address',
        name: 'AddressManagement',
        component: AddressManagementComponent,
        meta: {
          title: '地址管理 - EasyBuy',
          requiresAuth: true
        }
      },
      {
        path: 'orders-management',
        name: 'OrderManagement',
        component: () => import('@/views/order/OrderManagement.vue'),
        meta: {
          title: '订单管理 - EasyBuy',
          requiresAuth: true,
          requiresAdmin: true
        }
      }
    ]
  },
  {
    path: '/orders',
    name: 'OrderList',
    component: OrderList,
    meta: {
      title: '我的订单 - EasyBuy',
      requiresAuth: true
    }
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: Favorites,
    meta: {
      title: '我的收藏 - EasyBuy',
      requiresAuth: true
    }
  },
  {
    path: '/sell',
    name: 'SellPage',
    component: SellPage,
    meta: {
      title: '特卖专区 - EasyBuy'
    }
  },
  {
    path: '/order/confirmation/:cartItems/:totalAmount',
    name: 'OrderConfirmation',
    component: OrderConfirmation,
    meta: {
      title: '订单确认 - EasyBuy',
      requiresAuth: true // 需要登录才能访问
    }
  },
  {
    path: '/alipay/payment/:orderId',
    name: 'AlipayPayment',
    component: AlipayPayment,
    meta: {
      title: '支付宝支付 - EasyBuy',
      requiresAuth: true // 需要登录才能访问
    }
  },
  // 添加分类商品页面路由
  {
    path: '/category/:id',
    name: 'CategoryProducts',
    component: CategoryProducts,
    meta: {
      title: '分类商品 - EasyBuy'
    }
  },
  {
    path: '/test-highlight',
    name: 'TestHighlight',
    component: TestHighlight,
    meta: {
      title: '高亮测试 - EasyBuy'
    }
  },
  {
    path: '/highlight-test',
    name: 'HighlightTest',
    component: HighlightTest,
    meta: {
      title: '高亮功能测试 - EasyBuy'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/NotFound.vue'),
    meta: {
      title: '页面不存在 - EasyBuy'
    }
  }
]

//  创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由全局守卫
router.beforeEach((to, from, next) => {
  // 更新页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  
  // 检查登录状态
  const isLoggedIn = localStorage.getItem('userInfo') !== null
  const userInfo = isLoggedIn ? JSON.parse(localStorage.getItem('userInfo')) : null
  
  // 需要登录的页面
  if (to.meta.requiresAuth && !isLoggedIn) {
    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  // 需要管理员权限的页面
  if (to.meta.requiresAdmin && (!userInfo || !userInfo.isAdmin)) {
    // 如果不是管理员，显示错误信息并跳转到用户中心
    alert('您没有权限访问该页面')
    next({ name: 'UserCenter' })
    return
  }
  
  // 只允许游客访问的页面（如登录、注册）
  if (to.meta.requiresGuest && isLoggedIn) {
    next({ name: 'Home' })
    return
  }
  
  next()
})

// 路由后置守卫
router.afterEach((to, from) => {
  // 可以在这里添加统计代码或其他后置处理
  console.log(`路由跳转: ${from.path} -> ${to.path}`)
})

export default router //  暴露路由实例